package com.user.util;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Arrays;
import java.util.Objects;
import java.util.UUID;
import java.util.function.BooleanSupplier;

public class JedisUtil {
    private static JedisPool jedisPool;
    public static Jedis getJedis(){
        if(jedisPool == null){
            jedisPool = SpringBeanContextUtil.getBean(JedisPool.class);
            return jedisPool.getResource();
        }else{
            return jedisPool.getResource();
        }
    }

    public static void close(Jedis jedis){
        if (jedis != null){
            jedis.close();
        }
    }

    public static boolean setLock(BooleanSupplier booleanSupplier){
        boolean f = false;
        Jedis jedis = getJedis();
        String id = UUID.randomUUID().toString();
        String value = id.replace("-", "");
        System.out.println("reids随机值: "+ value);
        String set = jedis.set("lock", value, "nx", "ex", 100);
        if(Objects.equals("OK",set)){
            System.out.println("操作方法");
            f =booleanSupplier.getAsBoolean();
            Object lock = jedis.eval("if(redis.call('get',KEYS[1])==ARGV[1]) then return redis.call('del',KEYS[1]) else return 0 end",
                    Arrays.asList("lock"), Arrays.asList(value));
            System.out.println(lock);
        }else{
            System.out.println("锁被占用中");
        }
        jedis.close();
        return f;
    }
}
